import store from '@/store';
import router from './index';
import NProgress from 'nprogress'; // 进度条
import 'nprogress/nprogress.css'; // 进度条样式
import { appName, isProduction, isDynamicPermission } from '@/setting.js';
import { intoRecurse } from '@u/common.js';
import { setTmpCache, getTmpCache } from '@u/cache.js';
import translateIntoRouters from './addRoutes.js';

const whiteList = ['/login', '/404']; // 白名单

router.beforeEach(async(to, from, next) => { // 全局前置守卫
  // console.log(from, to);
  NProgress.start(); // 开始进度条

  const routerParams = to.params;
  if (routerParams) { // 通过路由参数处理页面缓存等问题
    if (routerParams.removeTagViews && routerParams.removeTagViews.length) { // 去除特定页面的 tagView ，必须放在清除缓存前
      routerParams.removeTagViews.map(tag => {
        store.commit('layout/removeTagViews', { name: tag });
      });
      delete routerParams.removeTagViews;
    }
    if (routerParams.removeAliveRoters && routerParams.removeAliveRoters.length) { // 去除特定页面的缓存
      routerParams.removeAliveRoters.map(aliveRoter => {
        store.commit('layout/removeAliveRoters', aliveRoter);
      });
      delete routerParams.removeAliveRoters;
    }
    if (routerParams.pages) { // 保存页面需要局部更新的字段
      store.commit('layout/setPages', routerParams.pages);
      delete routerParams.pages;
    }
  }

  if (to.meta && to.meta.title) { // 设置页面标题
    if (to.meta.isFullTitle) {
      document.title = to.meta.title;
    } else {
      document.title = appName + '-' + to.meta.title;
    }
  } else {
    document.title = appName;
  }

  if (to.query.token) { // 路径传token，第二种登录方式
    setTmpCache('token', to.query.token);
  }
  if (whiteList.includes(to.path) || whiteList.includes(to.name)) { // 是否需要权限
    next();
  } else {
    if (isProduction) {
      if (isDynamicPermission) {
        const indexPage = { path: '404' };
        if (!store.getters.userPermission.length) { // 没有获取权限
          const userPermission = await store.dispatch('user/getUserPermission'); // 获取权限
          if (!userPermission.length) { // 完全没有权限，跳转到登录页
            if (from.path == '/login') {
              next('/404');
            } else {
              next('/login');
            }
          } else { // 有权限

            if (!store.getters.userInfo.id) { // 获取用户信息
              await store.dispatch('user/getUserInfo');
            }

            intoRecurse(userPermission, (item, options) => { // 获取首页
              if (item.redirect) {
                indexPage.path = item.redirect;
                options.close = true;
              } else {
                if (item.meta && item.meta.type == 3) { // 找到第一个菜单
                  delete indexPage.path;
                  indexPage.name = item.name;
                  item.meta.isIndex = true;
                  options.close = true;
                }
              }
            });

            const { asyncRouters, affixRouters, modules, menus, functions, buttons } = translateIntoRouters(userPermission, (buttons, item) => { // 将权限转换为二维路由
              let path = item.redirect.replace('?token', `?token=${ getTmpCache('token') }`); // 处理并获取按钮权限
              path = path.replace('&token', `&token=${ getTmpCache('token') }`);
              buttons[item.name] = {
                name: item.name,
                title: item.meta && item.meta.title,
                redirect: path
              };
            });
            store.commit('layout/setAffixTagViews', affixRouters); // 重新获取 affixTagViews
            store.commit('user/setModulesPermission', modules); // 重新获取模块权限
            store.commit('user/setMenusPermission', menus); // 重新获取菜单权限
            store.commit('user/setFunctionsPermission', functions); // 重新获取功能权限
            store.commit('user/setButtonsPermission', buttons); // 重新获取按钮权限
            router.addRoutes([ // 动态添加路由
              ...asyncRouters,
              // 添加首页重定向，必须写在404前面
              { path: '/', redirect: { name: indexPage.name }},
              // 动态加载路由通配符，路由通配符必须写在最下面
              { path: '*', redirect: '/404' }
            ]);
            if (to.path == '/') { // 是否跳转到首页
              next(indexPage);
            } else {
              next({ ...to, replace: true }); // 不这样设置刷新页面会出现空白页
            }
          }
        } else {
          if (to.path == '/') { // 是否跳转到首页
            next(indexPage);
          } else {
            next();
          }
        }
      } else {
        if (getTmpCache('token')) {
          if (!store.getters.userInfo.id) { // 获取用户信息
            await store.dispatch('user/getUserInfo');
          }
          next();
        } else {
          next('/login');
        }
      }
    } else {
      next();
    }
  }
});

router.afterEach(() => { // 全局后置钩子
  NProgress.done(); // 完成进度条
});

export default router;
